<?php
/**
 * Created by windows.
 * User: cocoliu
 * Date: 2016/6/5
 * Time: 10:32
 */

namespace Libs\WeiXin;


class Sign extends Weixin
{
	//ASCII 码从小到大排序（字典序）排序组合URL,获取签名包
	public function getSignPackage() {
		$jsapiTicket = $this->getJsApiTicket();

		// 注意 URL 一定要动态获取，不能 hardcode.
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

		$timestamp = time();
		$nonceStr = $this->createNonceStr();

		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

		$signature = sha1($string);

		$signPackage = array(
			"appId"     => APPID,
			"nonceStr"  => $nonceStr,
			"timestamp" => $timestamp,
			"url"       => $url,
			"signature" => $signature,
			"rawString" => $string
		);
		return $signPackage;
	}

	//为获得JSSDK权限的签名算法
	private function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}

	//获得微信Api JS接口票据
	private function getJsApiTicket($cacheKey = '') {

		$cacheKey = $cacheKey ?: 'api_ticket';

		if ($ticket = S('apiTicket'))
		{
			$this->api_ticket = $ticket;
			return $ticket;
		}
		$curl = new \Libs\Curl\Curl;
			$accessToken = $this -> getAccessToken();
			// 如果是企业号用以下 URL 获取 ticket
			// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
			$res = json_decode($curl->get($url));
			$this->api_ticket = $res->ticket;
			S('apiTicket', $this->api_ticket, array('expire'=>7000));
		return $this->api_ticket;
	}

}